import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint,
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/logging-sensitive-info.md';
const DESCRIPTION = 'Avoid logging sensitive information such as passwords or tokens. Logging such data may lead to security breaches, especially in production environments.';

const sensitiveKeywords = ['password', 'passwd', 'pwd', 'secret', 'token', 'apikey'];

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => {
    return ts.isCallExpression(node);
  })
  .when((node: ts.CallExpression) => {
    if (!ts.isPropertyAccessExpression(node.expression)) { return false };

    const expr = node.expression;
    const caller = expr.expression.getText();
    const method = expr.name.getText();

    const isConsoleCall = caller === 'console' && ['log', 'info', 'warn', 'error'].includes(method);
    if (!isConsoleCall) { return false };

    // include key information
    for (const arg of node.arguments) {
      if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {
        const text = arg.text.toLowerCase();
        if (sensitiveKeywords.some(keyword => text.includes(keyword))) {
          return true;
        }
      }
    }

    return false;
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH,
  });
